package app

import (
	"errors"
	"fmt"
	"net/http"
	"os"
	"time"

	"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/stringutil"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/system"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/ginutil"

	Log "github.com/cihub/seelog"
)

type BrickApp struct{}

/**
 * 程序注册码校验
 * @param key 干扰密钥
 * @param isClose 验证失败时是否关闭程序
 * @return
 */
func (BrickApp) CheckPollCode(key string, isClose bool) bool {
	code := ReadConfigKey("App", "PollCode", "").(string)
	bl, _ := system.CheckPollCode(code, key)
	if bl {
		return true
	}

	if isClose {
		fmt.Println("程序注册码校验失败，关闭程序")
		Log.Error("程序注册码校验失败，关闭程序")
		os.Exit(0)
	}

	fmt.Println("程序注册码校验失败")
	Log.Error("程序注册码校验失败")

	return false
}

/**
 * 程序运行
 * @param InterceptorFunc 拦截函数
 */
func (ba BrickApp) Run(InterceptorFunc func(ctx ginutil.Context) bool) {
	Root := ReadConfigKey("System", "Root", "/webroot/").(string)
	Port := ReadConfigKey("System", "Port", "8080").(string)
	Title := ReadConfigKey("System", "Title", "").(string)
	Name := ReadConfigKey("System", "Name", "").(string)
	GinMode := ReadConfigKey("System", "Gin", "Release").(string)

	//DbNamedRules = ReadConfigKey("DataSource", "DbNamedRules", "common").(string) //common 通用数据库命名格式定义;bricks 自定义的格式

	go Cloud{}.RegistraCloud() //注册服务到注册中心

	httpServer := ginutil.GetGin(GinMode, Root, Port, InterceptorFunc)

	fmt.Println(stringutil.Append("================ ", Title, Name, "启动完毕,使用端口:", Port, ",时间:", time.Now().Format("2006-01-02 15:04:05"), " ================"))

	if err := httpServer.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
		if errors.Is(err, http.ErrServerClosed) {
			Log.Error("服务关闭")
			return
		}

		Log.Error("启动服务发生异常: ", err)
	}
}
